<title>选课搜索</title>

<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a><cite>选课</cite></a>
        <a><cite>个人选课</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header" id="layui-card-header-op"></div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">校区</label>
                            <div class="layui-input-block" id="campus-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">教师</label>
                            <div class="layui-input-block" lay-filter="teacher" id="teacher-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">时间</label>
                            <div class="layui-input-block" id="time-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <button class="layui-btn" lay-submit lay-filter="submit">确认</button>
                            <button id="refreshBtn" class="layui-btn" lay-submit lay-filter="refresh">重选</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">人数显示</div>
                <div class="layui-card-body" style="height: 500px;">
                    <div class="layui-carousel layadmin-carousel layadmin-dataview">
                        <div style="width: 100%; height:475px" id="LAY-index-dataview">
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="lineBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">选课页</a>
</script>
<script>
    layui.use(['jquery', 'table', "echarts", "carousel"], function(){
        var $ = layui.$, form = layui.form,
            echarts = layui.echarts, admin = layui.admin,
            view = layui.view;

        var url = window.location.href;
        var classname = url.substr(url.indexOf('=') + 1);   // 课程名
        document.getElementById("layui-card-header-op").innerText = decodeURI(classname);
        var classInfoList = [];     // 校区-教师-时间列表
        var sel_classinfo_list = [];
        var classInfoData;          // 存放课程信息
        var radioIdMap = {};        // radio id记录
        var radioId = 0;

        $.ajax({
            url: "/uclass/elective/classname?classname=" + classname,
            type: 'GET',
            dataType: 'JSON',
            complete: function (result) {
                // 获取课程列表数据
                result = result.responseJSON;
                if (result.status != 200){
                    layer.msg(result.message);
                } else {
                    classInfoData = result.data;
                    afterSuccess();
                    drawPersonNum(classInfoList);
                }

            }
        });
        function afterSuccess() {
            var data = classInfoData;
            var campusSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();
            for(var campus in data) {
                campusSet.add(campus);
                for (var teacher in data[campus]) {
                    teacherSet.add(teacher);
                    for (var time in data[campus][teacher]) {
                        timeSet.add(time);
                        classInfoList.push([campus, teacher, time]);
                    }
                }
            }
            if (campusSet.size == 1) {
                for (var campus of campusSet) {
                    addRadio("campus-radio", "campus", campus, true);
                }
            }else {
                for (var campus of campusSet) {
                    addRadio("campus-radio", "campus", campus, false);
                }
            }
            if (teacherSet.size == 1) {
                for (var teacher of teacherSet) {
                    addRadio("teacher-radio", "teacher", teacher, true);
                }
            } else {
                for (var teacher of teacherSet) {
                    addRadio("teacher-radio", "teacher", teacher, false);
                }
            }
            if (timeSet.size == 1) {
                for (var time of timeSet) {
                    addRadio("time-radio", "time", time, true);
                }
            } else {
                for (var time of timeSet) {
                    addRadio("time-radio", "time", time, false);
                }
            }
            form.render();
        }
        function addRadio(id, name, value, checked) {
            radioIdMap[value] = "radio-" + radioId++;
            var html = "<input type='radio' lay-filter='filter' name=" + name + " value='" + value + "' title='" + value + "' id='" + radioIdMap[value]  + "'";
            if (checked){
                html += " checked>";
            }else {
                html += ">";
            }
            $('#' + id).append(html);
        }
        // 监听radio
        form.on('radio(filter)', function(data){
            var campusSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();

            var sel_campus = $("input[name='campus']:checked").val();
            var sel_teacher = $("input[name='teacher']:checked").val();
            var sel_time = $("input[name='time']:checked").val();
            sel_classinfo_list = [];
            for(var index in classInfoList) {
                var campus = classInfoList[index][0];
                if(sel_campus == null || sel_campus == campus) {
                    var teacher = classInfoList[index][1];
                    if (sel_teacher == null || sel_teacher == teacher) {
                        var time = classInfoList[index][2];
                        if (sel_time == null || sel_time == time) {
                            sel_classinfo_list.push(classInfoList[index]);
                        }
                    }
                }
            }

            for(var classinfo in sel_classinfo_list) {
                campusSet.add(sel_classinfo_list[classinfo][0]);
                teacherSet.add(sel_classinfo_list[classinfo][1]);
                timeSet.add(sel_classinfo_list[classinfo][2]);
            }

            // 如果只剩下一个，则直接选中
            if (campusSet.size == 1) {
                for (var campus of campusSet) {
                    $("#" + radioIdMap[campus]).attr("checked",true);
                }
            }
            if(teacherSet.size == 1) {
                for(var teacher of teacherSet) {
                    $("#" + radioIdMap[teacher]).attr("checked",true);
                }
            }

            if(timeSet.size == 1) {
                for(var time of timeSet) {
                    $("#" + radioIdMap[time]).attr("checked",true);
                }
            }
            // 把剩余的radio disable
            for (var radioid in radioIdMap) {
                var id = radioIdMap[radioid];
                var value = document.getElementById(id).value;
                var name = document.getElementById(id).name;
                if (name == 'campus') {
                    if (!campusSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }else if (name == 'teacher') {
                    if (!teacherSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }else if (name == 'time') {
                    if (!timeSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }
            }
            form.render();

            // 如果只有一条数据即为选中，显示备注信息
            if (sel_classinfo_list.length === 1) {
                var campus = sel_classinfo_list[0][0];
                var teacher =  sel_classinfo_list[0][1];
                var time = sel_classinfo_list[0][2];
                var timeList = classInfoData[campus][teacher][time].time;
                var remark = "";
                var remarkSet = new Set();
                timeList.forEach(function (data) {
                    remarkSet.add(data.remark);
                });
                remarkSet.forEach(function (data) {
                   remark += data;
                });
                if (remark !== "") {
                    layer.msg("备注：" + remark);
                }
            }
            drawPersonNum(sel_classinfo_list);
        });

        // 监听提交
        form.on('submit(submit)', function (data) {
            debugger;
            if (classInfoList.length === 1) {
                sel_classinfo_list[0] = classInfoList[0];
            }
            if (sel_classinfo_list.length !== 1) {
                layer.msg("请选择");
                return;
            }
            var campus = sel_classinfo_list[0][0];
            var teacher = sel_classinfo_list[0][1];
            var time = sel_classinfo_list[0][2];
            var data = classInfoData[campus][teacher][time];
            admin.popup({
                title: "选课",
                area: ["420px", window.screen.availHeight * 0.9 + "px"],
                id: "LAY-popup-user-elective-confirm",
                success: function(layero, index) {
                    data['teacher'] = data['teachers'].toString();
                    var remark = "";
                    var timeList = data.time;
                    layui.each(timeList, function (index, item) {
                        remark += item.description;
                        if(item.classRoom.toString() !== "") {
                            remark += "-" + item.classRoom.toString();
                        }
                        if (item.remark !== "") {
                            remark += "-" + item.remark;
                        }
                        remark += "<br>";
                    });
                    data['remark'] = remark;
                    view(this.id).render("menu/elective/confirmClass", data).done(function () {
                        form.on("submit(LAY-user-back-submit)",function (formData) {
                            layer.close(index);
                            var load = layer.load(2);
                            var field = formData.field;
                            var content = {};
                            content['classCode'] = data.classCode;
                            content['classNum'] = data.classNum;
                            content['coin'] = field['coin'];
                            if (field.hasOwnProperty("buy")) {content['buy'] = true}
                            else {content['buy'] = false};
                            if (field.hasOwnProperty("retake")) {content['retake'] = true}
                            else {content['retake'] = false};
                            if (field.hasOwnProperty("adjust")) {content['adjust'] = true}
                            else {content['adjust'] = false};
                            $.ajax({
                                url: '/uclass/elective/save',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(content),
                                dataType: 'json',
                                complete: function (result) {
                                    layer.close(load);
                                    result = result.responseJSON;
                                    if (result.status === 200) {
                                        layer.msg("选课成功");
                                    }else {
                                        layer.msg(result.message);
                                    }
                                }
                            })
                        });
                    });
                }
            });
        });
        // 监听重选
        form.on("submit(refresh)", function (data) {
            sel_classinfo_list = [];
            $("input[name='campus']:checked").attr("checked", false);
            $("input[name='teacher']:checked").attr("checked", false);
            $("input[name='time']:checked").attr("checked", false)
            for (var radioid in radioIdMap) {
                $("#" + radioIdMap[radioid]).attr("disabled",false);
            }
            drawPersonNum(classInfoList);
            form.render();
        });

        // 人数画图
        function drawPersonNum(classinfos) {
            var classlist = [];
            var limitNums = [];
            var nowNums = [];
            var determineNums = [];
            for(var index in classinfos) {
                classlist.push(classinfos[index][0]  + "." + classinfos[index][1] + "--" + classinfos[index][2]);
                var limitNum = classInfoData[classinfos[index][0]][classinfos[index][1]][classinfos[index][2]].limitNum;
                var nowNum = classInfoData[classinfos[index][0]][classinfos[index][1]][classinfos[index][2]].nowNum;
                var determineNum = classInfoData[classinfos[index][0]][classinfos[index][1]][classinfos[index][2]].determineNum;
                limitNums.push(limitNum);
                nowNums.push(nowNum);
                determineNums.push(determineNum);
            }
            
            // 根据数量判断变成折线图还是柱状图
            var type = "line";
            if (classinfos.length <= 10) {
                type = "bar";
            }
            
            // 是否有滑动条,以及显示多少数据
            var len = 100;
            var slide = false;
            if (classinfos.length >= 20) {
                slide = true;
                len = parseInt(20 / classinfos.length * 100);
            }

            var personData = {
                title: {
                    text: decodeURI(classname),
                    textAlign: "auto",
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function(data)
                    {
                        var teacher = data[0].name.split(".")[1].split("--")[0] + "</br>";

                        var timeStart = data[0].name.indexOf("--");
                        var time = data[0].name.substr(timeStart + 2);
                        var timeList = time.split(",");
                        var timeDescription = "";
                        timeList.forEach(function (time) {
                            timeDescription += time + "</br>";
                        });

                        var personDescription = "";
                        data.forEach(function (classData) {
                            personDescription += classData.seriesName + "：" + classData.data + "</br>"
                        });

                        return teacher + timeDescription + personDescription;
                    }
                },
                legend: {
                    type: "scroll",
                    data: ["限选", "已选", "确定"]
                },
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    axisLabel : {
                        interval:0,
                        rotate:20,
                        formatter : function(params){
                            var index = params.indexOf("--");
                            var str = params.substr(0, index);
                            if (str.length > 11) {
                                return str.substr(0, 10) + ".."
                            }
                            return str;
                        }

                    },
                    data: classlist
                }],
                yAxis: [{
                    type: "value"
                }],
                series: [{
                    name: "限选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: limitNums
                }, {
                    name: "已选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: nowNums
                },{
                    name: "确定",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: determineNums
                }],
                dataZoom:{
                    type: 'slider',
                    show: slide,
                    height:10,//滚动条高度
                    start:0,//滚动条开始位置（共100等份）
                    end: len//结束位置（共100等份）
                }
            };
            var card= document.getElementById('LAY-index-dataview');
            var myChart = echarts.init(card, layui.echartsTheme);
            myChart.setOption(personData);
            myChart.resize();
        }

    });
</script>